<template>
    <div class="left-box" v-loading="loading">
        <router-link to="/console/" class="logo pic">
            <img src="@/assets/logo.png" />
        </router-link>
        <div class="btn-list">
            <template v-for="(value, key, index) in langList" :key="key">
                <span class="space" v-if="index !== 0"> | </span>
                <el-button link @click="switchLangHandle(key)">{{ value }}</el-button>
            </template>
        </div>
        <h1 class="tit">{{ $t('login.title') }}</h1>
        <el-alert :title="alertCon" :closable="false" v-if="alertCon" />
        <el-form :model="form" ref="loginRefs" :rules="rules">
            <el-form-item size="large" prop="account">
                <el-input v-model="form.account" :placeholder="$t('login.account_placeholder')" prefix-icon="User" />
            </el-form-item>
            <el-form-item size="large" prop="password">
                <el-input v-model="form.password" :type="isPwd ? 'password' : 'text'" :placeholder="$t('login.pwd_placeholder')" prefix-icon="Lock">
                    <template #append>
                        <el-button :icon="isPwd ? 'Hide' : 'View'" @click="isPwd = !isPwd" />
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-checkbox v-model="isRemember" :label="$t('login.remember')" />
            </el-form-item>
            <el-button size="large" class="login-btn" color="#F06423" @click="loginHandle">{{ $t('login.login_btn') }}</el-button>
            <el-button class="forget-btn" link @click="goPage('/forgetPwd')">{{ $t('login.forget_link') }}</el-button>
            <p class="tips-box">
                {{ $t('login.tips') }}
                <el-tooltip effect="dark" placement="right">
                    <template #content>
                        <div style="max-width: 275px">
                            <p>{{ $t('login.tips_tooltip1') }}</p>
                            <p>{{ $t('login.tips_tooltip2') }}</p>
                            <p>{{ $t('login.tips_tooltip3') }}</p>
                        </div>
                    </template>
                    <el-icon color="#1C77C3" size="16"><QuestionFilled /></el-icon>
                </el-tooltip>
            </p>
        </el-form>
        <p class="copyright">Copyright © 2025 The Education University of Hong Kong</p>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance } from 'element-plus'

import { useI18n } from 'vue-i18n'
import { setLocale, langList } from '@/locales/i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'

import AuthService from '@/api/auth'

import { useAuthStore } from '@/stores/auth'
import { useUserStore } from '@/stores/user'

import { goPage } from '@/utils/global'

const router = useRouter()
const authStore = useAuthStore()
const userStore = useUserStore()
const { locale, t } = useI18n<{ message: MessageSchema }, SupportedLocales>()
const loading = ref(false)
const alertCon = ref('')

// 语言切换
const switchLangHandle = (lang: SupportedLocales) => {
    setLocale(lang)
    locale.value = lang
}

// 表单
const loginRefs = ref<FormInstance>()
const isPwd = ref(true)
const isRemember = ref(!!localStorage.getItem('account'))
const form = reactive({
    account: localStorage.getItem('account') || 'admin',
    password: '123456',
})
const rules = {
    account: { required: true, message: t('login.account_tips'), trigger: 'blur' },
    password: { required: true, message: t('login.pwd_tips'), trigger: 'blur' },
}
const loginHandle = () => {
    if (!loginRefs.value) return

    loading.value = true
    if (isRemember.value && form.account) {
        localStorage.setItem('account', form.account)
    } else {
        localStorage.removeItem('account')
    }

    loginRefs.value.validate((valid, fields) => {
        if (valid) {
            AuthService.login(form)
                .then(res => {
                    if (res.user) {
                        handleLoginSuccess(res.user.id)
                    } else {
                        loading.value = false
                    }
                })
                .catch(() => {
                    loading.value = false
                })
        } else {
            loading.value = false
            console.error('error submit!', fields)
        }
    })
}

// 登录成功后
const handleLoginSuccess = (userId: number) => {
    const redirectPath = localStorage.getItem(`redirectPath_${userId}`)

    if (redirectPath && redirectPath !== '/') {
        localStorage.removeItem(`redirectPath_${userId}`) // 清除存储的路径
        router.push(redirectPath) // 跳转到之前的路由
    } else {
        router.push('/console/') // 默认跳转到首页
    }
}

onMounted(() => {
    authStore.scheduleTokenExpirationCheck()
    if (!authStore.isExpires) handleLoginSuccess(userStore.userinfoL?.id || 0)
})
</script>
